﻿using Microsoft.Win32;
using System.Collections.Generic;

namespace CloudManager
{
    internal class RegistryEditor 
    { 
        internal RegistryKey GetKey(string name, bool writable = false) 
        {
            
            var _tmpKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);

            return _tmpKey.OpenSubKey(name, writable);
        } 

        internal RegistryKey getRootKey(bool writable = false) 
        { 
            return GetKey("", writable); 
        } 

        public string GetSetting(string path, string valueName)
        {
            var defaultValue = string.Empty;            
            var k = GetKey(path, true);
            if (k == null) return defaultValue;

            return k.GetValue(valueName, defaultValue).ToString();
        }

        internal void SaveKey(string key, string value, string data)
        {
            if (!string.IsNullOrWhiteSpace(data))
            {
                var tmp = getRootKey(true);
                tmp = tmp.CreateSubKey(key);
                tmp.SetValue(value, data);
            }
            else
                if (!string.IsNullOrWhiteSpace(GetSetting(key, value)))
                    RemoveSetting(key, value, false);
        }

        public void RemoveKey(string key, string subKey)
        {
            var k = GetKey(key, true);
            
            if(k != null)
                k.DeleteSubKeyTree(subKey, false); 
        }
        
        public void RemoveSetting(string path,  string value,  bool clearDefault) 
        {
            var k = GetKey(path, true);

            if(k != null)
                k.DeleteValue(value, false); 
        } 


        public IEnumerable<string> GetSubKeyNames(string path)
        {
            return GetKey(path).GetSubKeyNames();
        }
    } 
} 